<!--  -->
<template>
  <div class="app-container">
    <el-tabs type="border-card" v-model="activeName" @tab-click="handleClick">
      <el-tab-pane label="角色权限配置" name="first">
        <el-button type="primary" @click="handleAddRole">添加角色</el-button>
        <el-table :data="roleList" style="width: 100%;margin-top:30px;" border="" stripe>
          <el-table-column align="center" label="角色名" width="220">
            <template slot-scope="scope">
              <template v-if="scope.row.temp_edit">
                <el-input v-model="scope.row.name" class="edit-input" size="small"/>
              </template>
              <span v-else>{{ scope.row.name }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="描述" width="220">
            <template slot-scope="scope">
              <template v-if="scope.row.temp_edit">
                <el-input v-model="scope.row.description" class="edit-input" size="small"/>
              </template>
              <span v-else>{{ scope.row.description }}</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作">
            <template slot-scope="scope">
              <el-button
                size="mini"
                type="primary"
                icon="el-icon-edit"
                @click="editMenuEvent(scope.row)"
              >编辑菜单权限</el-button>
              <template v-if="scope.row.temp_edit">
                <el-button
                  size="mini"
                  type="success"
                  icon="el-icon-circle-check-outline"
                  @click="saveRowEvent(scope.row)"
                >保存</el-button>
                <el-button
                  size="mini"
                  type="warning"
                  icon="el-icon-refresh"
                  @click="cancelRowEvent(scope.$index,scope.row)"
                >取消</el-button>
              </template>
              <template v-else>
                <el-button
                  size="mini"
                  type="primary"
                  icon="el-icon-edit"
                  @click="editRowEvent(scope.row)"
                >角色权限设置</el-button>
                <el-button
                  size="mini"
                  type="danger"
                  icon="el-icon-delete"
                  @click="removeRowEvent(scope.row)"
                >删除</el-button>
              </template>
            </template>
          </el-table-column>
        </el-table>
      </el-tab-pane>
      <el-tab-pane label="模块权限配置" name="second">
        <permission-table></permission-table>
      </el-tab-pane>
    </el-tabs>
    <el-dialog  width="35%" :visible.sync="dialogVisible" :title="dialogType">
      <el-form :model="roleData" label-width="80px" label-position="left">
        <el-form-item label="角色名">
          <el-input v-model="roleData.name" placeholder="角色名"/>
        </el-form-item>
        <el-form-item label="描述">
          <el-input
            v-model="roleData.description"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="描述"
          />
        </el-form-item>
        <el-form-item v-if="modelStatus" label="模块">
          <el-transfer
            v-model="model.modelValue"
            :data="model.modelData"
            :titles="['所有模块', '角色模块']"
            :button-texts="['删除', '添加']"
            filterable
            @change="handleChange"
            :render-content="renderContent"
          ></el-transfer>
        </el-form-item>
        <el-form-item v-else label="菜单">
          <el-tree
            ref="tree"
            :data="routesData"
            :props="defaultProps"
            :default-expanded-keys="defaultExpand"
            :default-checked-keys="defaultChecked"
            show-checkbox
            node-key="guid"
            class="permission-tree"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button v-if="modelStatus" type="primary" @click="confirmRole">确定</el-button>
        <el-button v-else type="primary" @click="addMenuRole">确定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  getRolesLikeRoleName,
  addRole,
  updateRoleModels,
  getModelsByRoleGuid,
  getModelsLikeModelName
} from "@/api/manage";
import { getRoleRouters, addRoleRouters } from "@/api/menu";
import permissionTable from "@/views/manage/permission/permissionTable";
//这里可以导入其他文件（比如：组件，工具js，第三方插件js，json文件，图片文件等等）
//例如：import 《组件名称》 from '《组件路径》';
const defaultRole = {
  key: "",
  name: "",
  description: "",
  routes: []
};
export default {
  //import引入的组件需要注入到对象中才能使用
  components: { permissionTable },
  data() {
    //这里存放数据
    return {
      roleList: [],
      activeName: "first",
      checkStrictly: false,
      routes: [],
      roleData: {},
      roleGuid: "",
      dialogVisible: false,
      role: Object.assign({}, defaultRole),
      dialogType: "编辑角色权限",
      routesData: [],
      defaultChecked: [],
      defaultExpand: [],
      defaultProps: {
        children: "children",
        label: "title"
      },
      model: {
        modelData: [],
        modelValue: []
      },
      modelStatus: false, //控制弹出框内容显示
      addValue: [],
      delValue: []
    };
  },
  //监听属性 类似于data概念
  computed: {
    // routesData() {
    //   console.log("routes", this.routes);
    //   return this.routes;
    // }
  },
  //监控data中的数据变化
  watch: {},
  //方法集合
  methods: {
    getRoles() {
      getRolesLikeRoleName().then(response => {
        this.roleList = response.body;
        this.roleList = this.roleList.map(v => {
          this.$set(v, "temp_edit", false);
          return v;
        });
      });
    },
    handleClick(tab, event) {
      console.log(tab, event);
    },
    handleAddRole() {
      this.roleList.unshift({ temp_edit: true });
      // this.role = Object.assign({}, defaultRole);
      // if (this.$refs.tree) {
      //   this.$refs.tree.setCheckedNodes([]);
      // }
      // this.dialogVisible = true;
    },
    saveRowEvent(row) {
      addRole(row).then(response => {
        this.getRoles();
      });
    },
    getAllModel() {
      this.model.modelData = [];
      this.model.modelValue = [];
      getModelsLikeModelName().then(response => {
        if (response.body != null) {
          //所有模型
          for (let index = 0; index < response.body.length; index++) {
            this.model.modelData.push({
              key: response.body[index].guid,
              label: response.body[index].name,
              description: response.body[index].description
            });
          }
        }
      });

      getModelsByRoleGuid(this.roleData.guid).then(response => {
        //角色所属模型
        if (response.body != null) {
          let modelKey = response.body.models;
          for (let index = 0; index < modelKey.length; index++) {
            this.model.modelValue.push(modelKey[index].guid);
          }
          console.log("modelValue", this.model.modelValue);
        }
      });
    },
    //编辑行事件
    editRowEvent(row) {
      this.dialogType = "编辑角色权限";
      this.dialogVisible = true;
      this.modelStatus = true;
      this.roleData = row;
      let data = { roleGuid: row.guid };
      console.log(row.guid);
      this.getAllModel();
    },
    //编辑菜单权限
    editMenuEvent(row) {
      this.dialogType = "编辑角色菜单权限";
      this.dialogVisible = true;
      this.modelStatus = false;
      this.roleData = row;
      this.checkStrictly = true;
      this.roleGuid = row.guid;
      const data = {
        rootGuid: "0f440c57-0615-489e-b456-96703cbdb7e6",
        roleGuid: row.guid
      };
      getRoleRouters(data).then(res => {
        this.routesData = res.body.children;
        const routerKey = res.body.children.filter(item => item.selected); //父节点被选中的数组
        console.log("routerKey", routerKey);
        console.log("defaultChecked", this.generateGuid(routerKey));
        this.defaultChecked = this.generateGuid(routerKey);
      });
    },
    generateGuid(routes) {
      let data = [];
      routes.forEach(route => {
        if (route.children === null && route.selected) {
          data.push(route.guid);
        }
        if (route.children) {
          const temp = this.generateGuid(route.children);
          if (temp.length > 0) {
            data = [...data, ...temp];
          }
        }
        // if (route.selected) {
        //   data.push(route.guid);
        // }
        // if (route.children) {
        //   const temp = this.generateGuid(route.children);
        //   if (temp.length > 0) {
        //     data = [...data, ...temp];
        //   }
        // }
      });
      return data;
    },
    cancelRowEvent(index, row) {
      this.roleList.splice(index, 1);
    },
    handleChange(value, direction, movedKeys) {
      let keyData = this.model.modelData.map(model => model.key);
      if (direction === "left") {
        for (let index = 0; index < movedKeys.length; index++) {
          if (keyData.includes(movedKeys[index])) {
            this.delValue.push(movedKeys[index]);
          }
          this.addValue = this.addValue.filter(
            item => item != movedKeys[index]
          );
        }
      } else {
        for (let index = 0; index < movedKeys.length; index++) {
          if (keyData.includes(movedKeys[index])) {
            this.addValue.push(movedKeys[index]);
          }
          this.delValue = this.delValue.filter(
            item => item != movedKeys[index]
          );
        }
      }
    },
    //添加菜单权限
    addMenuRole() {
      console.log("菜单:", this.routesData);
      // const checkedKey = this.$refs.tree.getCheckedKeys();
      // const checkedKey = this.$refs.tree.getHalfCheckedKeys();
      const checkedKey = [
        ...this.$refs.tree.getCheckedKeys(),
        ...this.$refs.tree.getHalfCheckedKeys()
      ];
      console.log("选中的key", checkedKey);
      const routers = {
        roleGuid: this.roleGuid,
        routers: checkedKey
      };
      addRoleRouters(routers).then(res => {});
    },
    generateRoutes(routes, basePath = "/") {
      const res = [];
      for (let route of routes) {
        // skip some route
        if (route.hidden) {
          continue;
        }
        const onlyOneShowingChild = this.onlyOneShowingChild(
          route.children,
          route
        );
        if (route.children && onlyOneShowingChild && !route.alwaysShow) {
          route = onlyOneShowingChild;
        }
        const data = {
          path: path.resolve(basePath, route.path),
          title: route.meta && route.meta.title
        };
        // recursive child routes
        if (route.children) {
          data.children = this.generateRoutes(route.children, data.path);
        }
        res.push(data);
      }
      return res;
    },
    handleEdit(row) {
      // this.dialogType = "edit";
      this.dialogVisible = true;
      this.checkStrictly = true;
      this.role = deepClone(scope.row);
      this.$nextTick(() => {
        const routes = this.generateRoutes(this.role.routes);
        this.$refs.tree.setCheckedNodes(this.generateArr(routes));
        // set checked state of a node not affects its father and child nodes
        this.checkStrictly = false;
      });
    },
    handleDelete({ $index, row }) {
      this.$confirm("确认删除此权限?", "Warning", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(async () => {
          await deleteRole(row.id);
          this.rolesList.splice($index, 1);
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        })
        .catch(err => {
          console.error(err);
        });
    },
    renderContent(h, option) {
      return (
        <el-popover
          placement="right"
          title={option.label}
          width="200"
          trigger="hover"
        >
          <span slot="reference">{option.label}</span>
        </el-popover>
      );
    },
    confirmRole() {
      const data = {
        addModelGuids: this.addValue,
        delModelGuids: this.delValue,
        roleGuid: this.roleData.guid
      };
      console.log("guid:", this.roleData.guid);
      console.log("add", this.addValue);
      console.log("del", this.delValue);
      updateRoleModels(data).then(response => {
        if (response.code === 100) {
          this.getAllModel();
        }
      });
    }
  },
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {
    //TODO后台返回路由列表和角色列表
    // this.getRoutes()
    this.getRoles();
  },
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() {},
  beforeCreate() {}, //生命周期 - 创建之前
  beforeMount() {}, //生命周期 - 挂载之前
  beforeUpdate() {}, //生命周期 - 更新之前
  updated() {}, //生命周期 - 更新之后
  beforeDestroy() {}, //生命周期 - 销毁之前
  destroyed() {}, //生命周期 - 销毁完成
  activated() {} //如果页面有keep-alive缓存功能，这个函数会触发
};
</script>
<style lang='scss' scoped>
//@import url(); 引入公共css类
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>